﻿/*
 * Programer: Jeffrey Padfield
 * Description: Seralizes information into XML Files.
 * Version: 1
 * Date: 01/27/2014
 */

using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace CWSaver.XML
{
    public class XmlSeralize
    {
        /// <summary>
        /// Default Constructor
        /// </summary>
        public XmlSeralize()
        {

        }

        /// <summary>
        /// Seralize data produced by program.
        /// </summary>
        /// <typeparam name="T">Type of data to seralize.</typeparam>
        /// <param name="fileName">Name of the file you want to use or create.</param>
        /// <param name="data">Information you want to save.</param>
        public void Seralize<T>(string fileName, T data)
        {
            XmlWriterSettings settings = new XmlWriterSettings {Indent = true};
            XmlSerializer ser = new XmlSerializer(typeof(T));

            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                using (XmlWriter writer = XmlWriter.Create(fs, settings))
                {
                    ser.Serialize(writer, data);
                }
            }
        }

        /// <summary>
        /// Deseralizes the xml file you send to it.
        /// </summary>
        /// <typeparam name="T">Type of data the xml holds.</typeparam>
        /// <param name="fileName">Name of xml tile to deseralize.</param>
        /// <returns>Deseralized data from the file.</returns>
        public T Deseralize<T>(string fileName)
        {
            T data;
            XmlSerializer deSerializer = new XmlSerializer(typeof (T));
            using (Stream readerStream = new FileStream(fileName, FileMode.Open))
            {
                data = (T) deSerializer.Deserialize(readerStream);
            }

            return data;
        }

    }
}
